//
//  KYTestViewController.m
//  KouyuDemo
//
//  Created by Attu on 2017/8/15.
//  Copyright © 2017年 Attu. All rights reserved.
//  评测页面

#import "KYTestViewController.h"
#import "KYTestTableViewCell.h"
#import "ATMicView.h"

@interface KYTestViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@property (weak, nonatomic) IBOutlet UIButton *testButton;
@property (nonatomic, strong) ATMicView *micView;  

@property (nonatomic, strong) NSArray *wordsArray;
@property (nonatomic, strong) NSArray *sentenceArray;
@property (nonatomic, strong) NSArray *paragraphArray;

@property (nonatomic, strong) NSArray *testArray;
@property (nonatomic, strong) NSString *testString;

@end

@implementation KYTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = 44.0f;
    [self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    switch (self.testType) {
        case KYTestType_Word:
            self.testArray = self.wordsArray;
            break;
        case KYTestType_Sentence:
            self.testArray = self.sentenceArray;
            break;
        case KYTestType_Paragraph:
            self.testArray = self.paragraphArray;
            break;
            
        default:
            break;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
    self.testString = [self.testArray firstObject];
    self.resultLabel.text = [NSString stringWithFormat:@"当前评测内容：%@", self.testString];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[KYTestEngine sharedInstance] stopEngine];
}

#pragma mark - Event
//开始录音评测
- (IBAction)onClickStartTest:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        if ([self.testString length] != 0) {
            self.resultLabel.text = [NSString stringWithFormat:@"当前评测内容：%@", self.testString];
        }
        [sender setTitle:@"结束" forState:UIControlStateNormal];
        [self.view addSubview:self.micView];
        
        //配置评测参数
        KYTestConfig *config = [[KYTestConfig alloc] init];
        config.coreType = self.testType;
        config.refText = self.testString;
        config.phonemeOption = KYPhonemeOption_KK;
        config.audioType = @"wav";
        config.sampleRate = 16000;
        config.sampleBytes = 2;
        config.scale = 10;
        __weak typeof(self) weakSelf = self;
        [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
            [weakSelf showResult:testResult];
        }];
    } else {
        [sender setTitle:@"开始评测" forState:UIControlStateNormal];
        [self.micView removeFromSuperview];
        [[KYTestEngine sharedInstance] stopEngine];
    }
}

//回放
- (IBAction)onClickRecordButton:(UIButton *)sender {
    [[KYTestEngine sharedInstance] playback];
}

//解析评测结果
- (void)showResult:(NSString *)result {
    printf("%s\n", [result UTF8String]);
    if([result rangeOfString:@"errId"].length > 0) {  //错误回调
        self.resultLabel.text = result;
    } else if ([result rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
        NSError *error;
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
        [self.micView updateVoiceViewWithVolume:soundIntensity/100.0f];
        self.resultLabel.text = result;        
    } else {  //评测结果回调
        NSError *error;
        NSString *str = @"";
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
        if(self.testType == KYTestType_Word)
        {
            NSArray *arr0=[NSArray arrayWithObjects:@"words", nil];
            NSArray *jsonwords = [jsonresult objectsForKeys:arr0 notFoundMarker:@"notFound"];
            NSArray *arr=[NSArray arrayWithObjects:@"phonemes",nil];
            NSDictionary *word = jsonwords[0][0];
            NSArray *ph = [word objectsForKeys:arr notFoundMarker:@"notFound"];
            if(![ph containsObject:@"notFound"])
            {
                str = @"/";
                for(int i=0; i<((NSArray *)ph[0]).count; i++)
                {
                    str = [str  stringByAppendingString:[NSString stringWithFormat:@"%@:%@ /", [ph[0][i] objectForKey:@"phoneme"], [ph[0][i] objectForKey:@"pronunciation"]]];
                }
            }
            self.resultLabel.text = [NSString stringWithFormat:@"总分：%@\n发音得分:%@\n音素得分:%@\n\n结果详情:\n%@", [jsonresult objectForKey:@"overall"], [jsonresult objectForKey:@"pronunciation"], str, result];
        }else if(self.testType == KYTestType_Sentence)
        {
            str = [str  stringByAppendingString:[NSString stringWithFormat:@"完整度:%@", [jsonresult objectForKey:@"integrity"]]];
            str = [str  stringByAppendingString:[NSString stringWithFormat:@"\n流利度:%@\n单词得分:/", [jsonresult objectForKey:@"fluency"]]];
            NSArray *arr0=[NSArray arrayWithObjects:@"words", nil];
            NSArray *jsonwords = [jsonresult objectsForKeys:arr0 notFoundMarker:@"notFound"];
            for(int i=0; i<((NSArray *)jsonwords[0]).count; i++)
            {
                str = [str  stringByAppendingString:[NSString stringWithFormat:@"%@:%@ /", [[jsonwords[0][i] objectForKey:@"word"] stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]], [[jsonwords[0][i] objectForKey:@"scores"] objectForKey:@"overall"]]];
            }
            self.resultLabel.text = [NSString stringWithFormat:@"总分：%@\n发音得分:%@\n%@\n\n结果详情:\n%@", [jsonresult objectForKey:@"overall"], [jsonresult objectForKey:@"pronunciation"], str, result];
        }else if(self.testType == KYTestType_Paragraph) {
            self.resultLabel.text = result;
        }
    }
}


#pragma mark - TableView Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.testArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    KYTestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestCell" forIndexPath:indexPath];
    cell.contentLabel.text = self.testArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.textField.text = @"";
    self.testString = self.testArray[indexPath.row];
    self.resultLabel.text = [NSString stringWithFormat:@"当前评测内容：%@", self.testString];
}

#pragma mark - UITextField

- (void)textFieldDidChange:(UITextField *)textField {
    self.testString = textField.text;
    self.resultLabel.text = [NSString stringWithFormat:@"当前评测内容：%@", textField.text];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Init

- (NSArray *)wordsArray {
    if (!_wordsArray) {
        _wordsArray = @[@"hello", @"happy", @"new", @"year", @"merry", @"christmas", @"apple", @"english", @"china"];
    }
    return _wordsArray;
}

- (NSArray *)sentenceArray {
    if (!_sentenceArray) {
        _sentenceArray = @[@"Let me introduce myself.", @"It’s nice meeting you.", @"I’d like to introduce my friend.", @"You mean a lot to me.", @"I’m Looking Forward to It.", @"Today is a great day.", @"Are you making progress?", @"That's a great idea!", @"Please say hello to your mother for me."];
    }
    return _sentenceArray;
}

- (NSArray *)paragraphArray {
    if (!_paragraphArray) {
        _paragraphArray = @[
                            @"This is my room. Near the window there is a desk. I often do my homework at it. You can see some books, some flowers in a vase, a ruler and a pen. On the wall near the desk there is a picture of a cat. There is a clock above the end of my bed. I usually put my shoe under my bed. Of course there is a chair in front of the desk. I sit there and I can see the trees and roads outside.",
                            @"Mom bought me a pair of skating shoes at my fifth birthday. From then on, I developed the hobby of skating. It not only makes me stronger and stronger, but also helps me know many truths of life. I know that it is normal to fall, and if only you can get on your feet again and keep on moving, you are very good!",
                            @"What do you know about the sea? Some people know about it, but others don’t. The sea looks beautiful on a fine sunny day, the sea is very big. In the world, there is more sea than land. Do you know Hainan Island? It’s really very nice. We can see beaches, trees and the sea. We can swim and visit a lot of beautiful places.",
                            @"Computers are changing our life. You can do a lot of things with a computer. Such as, you can use a computer to write articles, watch video CDs, play games and do office work. But the most important use of a computer is to join the Internet.We don’t need to leave home to borrow books from a library or to do shopping in a supermarket.",
                            @"Spring is a delightful season. The temperatures are moderate, and the blooming trees and flowers make the city bright with colors. This is the time when we can begin to wear lighter and more brightly colored clothes and go outdoors more often. Smaller children like to bring their kites out to the spacious square. Also I enjoy going back to the village on this holiday after being in the city for the winter months."];

    }
    return _paragraphArray;
}

- (ATMicView *)micView {
    if (!_micView) {
        _micView = [[ATMicView alloc] initWithFrame:CGRectMake(0, 0, 100, 100) lineWidth:2 linceColor:[UIColor whiteColor] colidColor:[UIColor whiteColor]];
        _micView.center = self.view.center;
    }
    return _micView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
